import Table from '@/components/rewardTable';
import { Row, Col, Image, Empty, Spin, message } from 'antd';
import { Button } from 'antd';
import React, { useEffect, useState } from "react";
import { useTranslation } from 'react-i18next';
// import {ethers} from 'ethers'
import group from '@/assets/photos/group.png';
import './nft.scss';
import { Divider } from 'antd';
import { get_user_reward, get_user_nft_staking_record } from '@/utils/mixin.ts'
import { main } from '@/utils/eth'
import { nftStake, unstake, getHoldTokens } from '@/utils/eth'
export default () => {
    const [spinning, setSpinning] = React.useState(false);
    const { t } = useTranslation();
    const [tableData, setTableData] = useState([])
    const [ntf, setNtf] = useState([])
    const dateTab = (dateString) => {
        const timestamp = dateString.updated_at * 1000; // 将时间戳乘以1000以转换为毫秒

        const dateObject = new Date(timestamp);

        const year = dateObject.getFullYear();
        const month = String(dateObject.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
        const day = String(dateObject.getDate()).padStart(2, '0');

        const formattedDate = `${year}-${month}-${day}`;
                return formattedDate;
    };
    const txtDis = (str) => {
        str = str.address
        const firstFour = str.slice(0, 4);
        const lastFour = str.slice(-4);
        const maskedString = `${firstFour}****${lastFour}`;
        return maskedString;
      };

      const nftStakeMain = () => {
        setSpinning(true);
        getHoldTokens().then(res => {
            console.log(res)
            setSpinning(false);
            if(!res || !res.length) return message.error('钱包内没有可供质押的NFT')
            nftStake(res[0]).then(res => {
                message.success('质押成功')
                get_user_mint_record()
                setSpinning(false);
            }).catch(err => {
                message.error('质押失败')
                setSpinning(false);
            })
        }).catch(err => {
            message.error('获取id失败')
            setSpinning(false);
        })
        
      }

      const unstakeMain = () => {
        setSpinning(true);
        unstake().then(res => {
            if(res.status == 'No staking') {
                setSpinning(false);
                return message.info('无质押')
            }
            message.success('取消成功')
            get_user_mint_record()
            setSpinning(false);
        }).catch(err => {
            message.error('取消失败')
            setSpinning(false);
        })
      }
   
    const columns = [
        {
            title: t('Deposit Address'),
            dataIndex: 'address',
            render: (text, record) => <span>{txtDis(text)}</span>
        },
        {
            title: t('Total'),
            dataIndex: 'token_id',
            render: (text, record) => <span>1</span>
        },
        {
            title: t('System Confirmation Time'),
            dataIndex: 'updated_at',
            render: (text, record) => <span>{dateTab(text)}</span>
        }
    ];
    
    const get_user_mint_record = async () => {
        const res = await get_user_nft_staking_record({email: localStorage.getItem('email')})
        setTableData(res.data)
        const res1 = await get_user_reward({email: localStorage.getItem('email')})
        setNtf(res1.data)
        console.log(ntf)
    }

    useEffect(() => {
        // 这里是 componentDidMount 的逻辑
        // console.log("Component is mounted");
        // const res = get_platform_trade({currency: 'BNB'})
        
        // 如果有清理逻辑，例如清理定时器，可以在这里添加
        // return () => {
        //   console.log("Component will unmount");
        //   // 清理逻辑
        // };
        get_user_mint_record()
      }, []);  // 空数组表示只在组件挂载时执行

    return (
        <>
        <Spin spinning={spinning} fullscreen />
        <Row className="netContent">
            
            <Col flex={1} sm={24} md={24} lg={24} xl={12} className="side">
                <p className="nft-records">
                    {t('NFT Staking')}
                </p>
                <Row>
                    <Col span={24} className="box ">
                        <Row align="middle" justify="space-around" wrap={false}>
                            <Col
                                span={8}
                                style={{
                                    position: 'relative',
                                    display: 'flex',
                                    justifyContent: 'center',
                                    alignItems: 'end'
                                }}>
                                <img src={group} className='groupImg' />
                            </Col>
                            <Col>
                                <div className="btnbox">
                                    <Button className="btn" onClick={() => {nftStakeMain()}}>{t('Stake NFT')}</Button>
                                    <Button className="btn" onClick={() => {unstakeMain()}}>{t('Unstaking')}</Button>
                                </div>
                            </Col>
                        </Row>
                    </Col>
                </Row>
            </Col>
            <Col flex={1} sm={24} md={24} lg={24} xl={12} className="sideTwo">
                <Row>
                    <Col span={24} className="box">
                        <Row justify="space-between" align="middle" style={{ height: '100%' }}>
                            <Col span={8} className="reward-left" flex={1}>
                                <h3 className="currentReward">{t("Today's Rewards")}</h3>
                                <div className='shi'>
                                    <h3 className="bnb"><span>{ntf.length ? ntf[0].nft_reward : '0.00'} </span>BNB</h3>
                                </div>
                            </Col>
                            {/* <Col span={8} className="reward-right btnbox">
                                <h3 className="title_">{t('Claimable')}：130.00个</h3>
                                <Button style={{ flex: '1 1' }}>{t('Withdraw')}</Button>
                            </Col> */}
                        </Row>
                    </Col>
                </Row>
            </Col>
            <Col flex={1} sm={24} md={24} lg={24} xl={12} className="sideThree" style={{ padding: '0' }}>
                <p className="nft-records">
                    {t('NFT Staking Records')}
                </p>

                <div style={{ borderRadius: '20px' }}>
                    {tableData.length ? <Table columns={columns} dataSource={tableData} /> : <Empty description={false}/>}
                </div>
            </Col>
        </Row>
        </>
    );
};
